package com.ruoyi.wechat.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.wechat.common.Constants;
import com.ruoyi.wechat.common.ServiceException;
import com.ruoyi.wechat.config.WxPayV3Bean;
import com.ruoyi.wechat.domain.AppUser;
import com.ruoyi.wechat.domain.Order;
import com.ruoyi.wechat.domain.vo.AjaxResult;
import com.ruoyi.wechat.mapper.OrderMapper;
import com.ruoyi.wechat.service.WxPayService;
import com.ruoyi.wechat.utils.LoginHelper;
import com.ruoyi.wechat.utils.WXPayUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.wechat.pay.java.core.http.Constant.*;

/**
 * @author lsh
 * @ClassName WxPayServiceImpl
 * @description: TODO
 * @date 2023年10月24日
 */
@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    private static final Logger logger = LoggerFactory.getLogger(WxPayServiceImpl.class);

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private WxPayV3Bean wxPayV3Bean;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> prePay(Long orderId) throws Exception {
        return trans(orderId);
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> trans(Long orderId) throws Exception {
        String url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        Order order = orderMapper.selectById(orderId);
        if (Constants.Order.PAY_STATUS_2.getValue().equals(order.getPayStatus())) {
            return prePay(order);
        }
        if (!Constants.Order.PAY_STATUS_1.getValue().equals(order.getPayStatus()) && !Constants.Order.PAY_STATUS_2.getValue().equals(order.getPayStatus())) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "订单不可支付");
        }

        AppUser appUser = LoginHelper.getSession().getAppUser();
        if(BigDecimal.ZERO.compareTo(order.getTotalAmount()) >= 0){
            //保存订单
            order.setPayStatus(Constants.Order.PAY_STATUS_3.getValue());
            order.setRealPayAmount(order.getTotalAmount());
            order.setPayMethod(Constants.Order.PAY_METHOD_0.getValue());
            orderMapper.updateById(order);
            return null;
        }
        //根据支付方式设置对应支付信息
        if (Constants.Order.PAY_METHOD_1.getValue().equals(order.getPayMethod())) {
            String openid = appUser.getOpenid();
            order.setAppUserId(openid);
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        //请求URL
        HttpPost httpPost = new HttpPost(url);
        // 构建请求体的 JSON 对象
        JSONObject reqData = new JSONObject();
        reqData.put("appid", wxPayV3Bean.getAppId());
        reqData.put("mchid", wxPayV3Bean.getMchId());
        reqData.put("description", "商品描述");
        reqData.put("out_trade_no", order.getTradeNo());
        reqData.put("notify_url", wxPayV3Bean.getNotifyUrl());

        JSONObject amount = new JSONObject();
        amount.put("total", order.getTotalAmount().multiply(new BigDecimal(100)).intValue());
        amount.put("currency", "CNY");
        reqData.put("amount", amount);
        // 构建 combine_payer_info 对象
        JSONObject payerInfo = new JSONObject();
        payerInfo.put("openid", order.getAppUserId());
        reqData.put("payer", payerInfo);
        // 将 JSON 对象转换为字符串
        String reqBody = reqData.toString();
        String token = WXPayUtil.getToken("POST", url, reqBody);

        //设置请求体和请求头
        StringEntity entity = new StringEntity(reqBody, "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Authorization", token);

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        JSONObject res = null;
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                String resStr = EntityUtils.toString(response.getEntity());
                //处理成功
                System.out.println("success,return body = " + resStr);
                res = JSONObject.parseObject(resStr);
            } else if (statusCode == 204) { //处理成功，无返回Body
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }
        //构造支付参数
        String prepayId = res.getString("prepay_id");

        Map<String, Object> params = new HashMap<>();
        Long timeStamp = System.currentTimeMillis() / 1000;
        params.put("timeStamp", timeStamp.toString());
        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        params.put("nonceStr", substring);
        String signatureStr = Stream.of(wxPayV3Bean.getAppId(), String.valueOf(timeStamp), substring, "prepay_id=" + prepayId)
                .collect(Collectors.joining("\n", "", "\n"));
        String sign = WXPayUtil.getSign(signatureStr, wxPayV3Bean.getKeyPath());
        params.put("paySign", sign);
        params.put("package", "prepay_id=" + prepayId);
        params.put("tradeNo", order.getTradeNo());
        log.info("-----------------------调用下单方法应答对象：" + params);

        //保存订单
        order.setPayStatus(Constants.Order.PAY_STATUS_2.getValue());
        order.setRealPayAmount(order.getTotalAmount());
        order.setPrepayId(prepayId);
        orderMapper.updateById(order);
        logger.info("下单订单信息：{}", JSON.toJSONString(order));

        return params;
    }

    /**
     * 微信预下单
     *
     * @param order
     * @return
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     * @throws IOException
     * @throws URISyntaxException
     * @throws InvalidKeyException
     */
    public Map<String, Object> prePay(Order order) throws NoSuchAlgorithmException, SignatureException, IOException, URISyntaxException, InvalidKeyException {
        Map<String, Object> params = new HashMap<>();
        Long timeStamp = System.currentTimeMillis() / 1000;
        params.put("timeStamp", timeStamp.toString());
        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        params.put("nonceStr", substring);
        String signatureStr = Stream.of(wxPayV3Bean.getAppId(), String.valueOf(timeStamp), substring, "prepay_id=" + order.getPrepayId())
                .collect(Collectors.joining("\n", "", "\n"));
        String sign = WXPayUtil.getSign(signatureStr, wxPayV3Bean.getKeyPath());
        params.put("paySign", sign);
        params.put("package", "prepay_id=" + order.getPrepayId());
        params.put("tradeNo", order.getTradeNo());
        log.info("-----------------------调用下单方法应答对象：" + params);

        //保存订单
        order.setPayStatus(Constants.Order.PAY_STATUS_2.getValue());
        order.setRealPayAmount(order.getTotalAmount());
        orderMapper.updateById(order);
        logger.info("下单订单信息：{}", JSON.toJSONString(order));
        return params;
    }


    /**
     * 合单支付
     *
     * @param orderId
     * @param request0
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> combTrans(Long orderId, HttpServletRequest request0) throws Exception {
        Order order = orderMapper.selectById(orderId);
        if (!Constants.Order.PAY_STATUS_1.getValue().equals(order.getPayStatus())) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "订单已过期，请重新下单");
        }

        AppUser appUser = LoginHelper.getSession().getAppUser();
        //根据支付方式设置对应支付信息
        if (Constants.Order.PAY_METHOD_1.getValue().equals(order.getPayMethod())) {
            String openid = appUser.getOpenid();
            order.setAppUserId(openid);
        }
        String url = "https://api.mch.weixin.qq.com/v3/combine-transactions/jsapi";

        CloseableHttpClient httpClient = HttpClients.createDefault();
        //请求URL
        HttpPost httpPost = new HttpPost(url);
        // 构建请求体的 JSON 对象
        JSONObject reqData = new JSONObject();
        reqData.put("combine_appid", wxPayV3Bean.getAppId());
        reqData.put("combine_mchid", wxPayV3Bean.getMchId());
        reqData.put("combine_out_trade_no", order.getTradeNo());
        //子单信息
        JSONObject subOrder = new JSONObject();
        subOrder.put("mchid", wxPayV3Bean.getMchId());
        subOrder.put("attach", "米丹分店");
        subOrder.put("out_trade_no", order.getTradeNo());
        subOrder.put("description", "米丹分店购物");
        //子单金额
        JSONObject subAmt = new JSONObject();
        subAmt.put("total_amount", 60);
        subAmt.put("currency", "CNY");
        subOrder.put("amount", subAmt);
        //支付者
        JSONObject payer = new JSONObject();
        payer.put("openid", order.getAppUserId());

        reqData.put("sub_orders", new JSONObject[]{subOrder});
        reqData.put("combine_payer_info", payer);
        reqData.put("notify_url", wxPayV3Bean.getNotifyUrl());

        // 将 JSON 对象转换为字符串
        String reqBody = reqData.toString();

        WXPayUtil wxPayUtil = new WXPayUtil();
        String token = wxPayUtil.getToken("POST", url, reqBody);

        StringEntity entity = new StringEntity(reqBody, "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Authorization", token);

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
            } else if (statusCode == 204) { //处理成功，无返回Body
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }


//
//        String prepayId = response.getPrepayId();
//
//        Map<String, Object> params = new HashMap<>();
//        Long timeStamp = System.currentTimeMillis() / 1000;
//        params.put("timeStamp", timeStamp.toString());
//        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
//        params.put("nonceStr", substring);
//        String signatureStr = Stream.of(wxPayV3Bean.getAppId(), String.valueOf(timeStamp), substring, "prepay_id=" + prepayId)
//                .collect(Collectors.joining("\n", "", "\n"));
//        String sign = WXPayUtil.getSign(signatureStr, wxPayV3Bean.getKeyPath());
//        params.put("paySign", sign);
//        params.put("package", "prepay_id=" + prepayId);
//        params.put("tradeNo", order.getTradeNo());
//        log.info("-----------------------调用下单方法应答对象：" + params);
//
//        //保存订单
//        order.setPayStatus(Constants.Order.PAY_STATUS_2.getValue());
//        order.setRealPayAmount(totalAmt);
//        orderMapper.updateById(order);
//
//        //开始
//        Order order = orderMapper.selectById(orderId);
//        if (!Constants.Order.PAY_STATUS_1.getValue().equals(order.getPayStatus()) ){
//            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR,"订单已过期，请重新下单");
//        }
//
//        AppUser appUser = LoginHelper.getLoginUser().getAppUser();
//        //根据支付方式设置对应支付信息
//        if (Constants.Order.PAY_METHOD_1.getValue().equals(order.getPayMethod())) {
//            String openid = appUser.getOpenid();
//            order.setAppUserId(openid);
//        }
//
//        logger.info("下单订单信息：{}", JSON.toJSONString(order));


        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createOrder2(Long orderId, HttpServletRequest request0) throws Exception {
        Order order = orderMapper.selectById(orderId);
        if (!Constants.Order.PAY_STATUS_1.getValue().equals(order.getPayStatus())) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "订单已过期，请重新下单");
        }

        AppUser appUser = LoginHelper.getSession().getAppUser();
        //根据支付方式设置对应支付信息
        if (Constants.Order.PAY_METHOD_1.getValue().equals(order.getPayMethod())) {
            String openid = appUser.getOpenid();
            order.setAppUserId(openid);
        }

        logger.info("下单订单信息：{}", JSON.toJSONString(order));

        //金额单位：分
        Amount amount = new Amount();
        BigDecimal totalAmt = order.getTotalAmount().multiply(BigDecimal.valueOf(100L));
        amount.setTotal(totalAmt.intValue());
        amount.setCurrency("CNY");
        // 创建预支付订单的请求对象
        PrepayRequest prepayRequest = new PrepayRequest();
        //amount.setTotal(1);
        prepayRequest.setAmount(amount);
        prepayRequest.setAppid(wxPayV3Bean.getAppId());
        prepayRequest.setMchid(wxPayV3Bean.getMchId());
        prepayRequest.setNotifyUrl(wxPayV3Bean.getNotifyUrl());
//        prepayRequest.setDescription(req.getDescription());
        prepayRequest.setDescription("商品描述的很好");
        prepayRequest.setOutTradeNo(order.getTradeNo());
//        prepayRequest.setAttach(req.getOrderType());
        if (!ObjectUtils.isEmpty(order.getTag())) {
            prepayRequest.setAttach(order.getTag().toString());
        }

        //根据token拿到openid,指定该预支付订单的支付者身份
        //String token = request.getHeader("token");
        //Map<String, Object> openMap = wechatUserMapper.getOpenIdByToken(token);
        Payer payer = new Payer();
        //payer.setOpenid(openMap.get("openId").toString());
        payer.setOpenid(order.getAppUserId());
        prepayRequest.setPayer(payer);

        // 使用自动更新平台证书的RSA配置，配置微信支付的自动证书管理功能
        Config config = new RSAAutoCertificateConfig.Builder()
                .merchantId(wxPayV3Bean.getMchId())
                .privateKeyFromPath(wxPayV3Bean.getKeyPath())
                .merchantSerialNumber(wxPayV3Bean.getMchSerialNo())
                .apiV3Key(wxPayV3Bean.getApiKey())
                .build();
        // 构建service,用于处理JSAPI支付相关的操作
        JsapiService service = new JsapiService.Builder().config(config).build();
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(prepayRequest);

        String prepayId = response.getPrepayId();

        Map<String, Object> params = new HashMap<>();
        Long timeStamp = System.currentTimeMillis() / 1000;
        params.put("timeStamp", timeStamp.toString());
        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        params.put("nonceStr", substring);
        String signatureStr = Stream.of(wxPayV3Bean.getAppId(), String.valueOf(timeStamp), substring, "prepay_id=" + prepayId)
                .collect(Collectors.joining("\n", "", "\n"));
        String sign = WXPayUtil.getSign(signatureStr, wxPayV3Bean.getKeyPath());
        params.put("paySign", sign);
        params.put("package", "prepay_id=" + prepayId);
        params.put("tradeNo", order.getTradeNo());
        log.info("-----------------------调用下单方法应答对象：" + params);


/*
        //保存订单信息
        try {
            String accountUserId = accountUserMapper.getAccountUserId(req.getAccountNumber().toString());
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("id", IdTool.getIdStr());
            orderMap.put("accountUserId", accountUserId);
            orderMap.put("appUserId", openMap.get("id"));
            orderMap.put("payOpenId", openMap.get("openId"));
            orderMap.put("orderType", req.getOrderType());
            orderMap.put("orderDate", DateUtil.getTime());
            orderMap.put("orderStatus", "0");
            orderMap.put("orderPrice", req.getAmount());
            orderMap.put("prepayId", response.getPrepayId());
            orderMap.put("tradeNo", tradeNo);
            log.info("-----------------------本次支付订单信息：" + orderMap);
            orderMapper.insertOrder(orderMap);
            return AjaxResult.defaultSuccess(params);
        } catch (Exception e) {
            throw new ApiException(e.toString());
        }*/


        //保存订单
        order.setPayStatus(Constants.Order.PAY_STATUS_2.getValue());
        order.setRealPayAmount(totalAmt);
        orderMapper.updateById(order);
        return params;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult payNotify(HttpServletRequest request) throws Exception {
        //读取请求体的信息
        ServletInputStream inputStream = request.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s;
        //读取回调请求体
        while ((s = bufferedReader.readLine()) != null) {
            stringBuffer.append(s);
        }
        String s1 = stringBuffer.toString();
        String timestamp = request.getHeader(WECHAT_PAY_TIMESTAMP);
        String nonce = request.getHeader(WECHAT_PAY_NONCE);
        String signType = request.getHeader("Wechatpay-Signature-Type");
        String serialNo = request.getHeader(WECHAT_PAY_SERIAL);
        String signature = request.getHeader(WECHAT_PAY_SIGNATURE);
        // 如果已经初始化了 RSAAutoCertificateConfig，可直接使用
        // 没有的话，则构造一个
        NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(wxPayV3Bean.getMchId())
                .privateKeyFromPath(wxPayV3Bean.getKeyPath())
                .merchantSerialNumber(wxPayV3Bean.getMchSerialNo())
                .apiV3Key(wxPayV3Bean.getApiKey())
                .build();
        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(config);
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serialNo)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                // 若未设置signType，默认值为 WECHATPAY2-SHA256-RSA2048
                .signType(signType)
                .body(s1)
                .build();
        Transaction parse = parser.parse(requestParam, Transaction.class);
        log.info("-----------------------parse = " + parse);

        try {
            //根据订单号查询待支付的订单
            LambdaQueryWrapper<Order> orderQuery = new LambdaQueryWrapper<>();
            orderQuery.eq(Order::getTradeNo, parse.getOutTradeNo());
            Order order = orderMapper.selectOne(orderQuery);
            if (Constants.Order.PAY_STATUS_3.getValue().equals(order.getPayStatus())) {
                log.info("-----------------------该订单：" + parse.getOutTradeNo() + "已经进行回调，不可重复回调");
                return AjaxResult.success();
            }
            order.setPayStatus(Constants.Order.PAY_STATUS_3.getValue());
            order.setDelvStatus(Constants.Order.DELV_STATUS_1.getValue());
            orderMapper.updateById(order);
        } catch (Exception e) {
            throw new ServiceException(e.toString());
        }
        log.info("-----------------------回调完成-----------------------");
        return AjaxResult.success();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Transaction queryPayOrder(String tradeNo) {
        LambdaQueryWrapper<Order> orderQuery = new LambdaQueryWrapper<>();
        orderQuery.eq(Order::getTradeNo, tradeNo);
        Order order = orderMapper.selectOne(orderQuery);
//        if (status.equals("1")) {
//            return AjaxResult.defaultSuccess("SUCCESS");
//        }
        // 使用自动更新平台证书的RSA配置，配置微信支付的自动证书管理功能
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(wxPayV3Bean.getMchId())
                        .privateKeyFromPath(wxPayV3Bean.getKeyPath())
                        .merchantSerialNumber(wxPayV3Bean.getMchSerialNo())
                        .apiV3Key(wxPayV3Bean.getApiKey())
                        .build();
        // 构建service,用于处理JSAPI支付相关的操作
        JsapiService service = new JsapiService.Builder().config(config).build();

        //根据商户订单号查询支付订单
        QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();
        queryRequest.setMchid(wxPayV3Bean.getMchId());
        queryRequest.setOutTradeNo(tradeNo);
        Transaction transaction = service.queryOrderByOutTradeNo(queryRequest);
        log.info("-----------------------支付状态：" + transaction.getTradeState());
        //updateAccountDetail(transaction);
        return transaction;
    }

    /**
     * 时间+id为订单号
     * @param
     * @return
     *//*
    public String getTradeNo() {
        String idStr = IdTool.getIdStr();
        long timestamp = DateUtil.getDate();
//        //序列号是为了保证同一毫秒内生成的订单号的唯一性
//        AtomicInteger sequence = new AtomicInteger(0);
//        int nextSequence = sequence.getAndIncrement();
//
        try {
//            MessageDigest md = MessageDigest.getInstance("MD5");
//            byte[] messageDigest = md.digest(String.valueOf(nextSequence).getBytes());
//
//            BigInteger no = new BigInteger(1, messageDigest);
//            String encrypted = no.toString(10); // 将十六进制转为十进制表示的字符串
//
//            // 如果加密结果长度超过20位，则截取前20位
//            if (encrypted.length() > 20) {
//                encrypted = encrypted.substring(0, 20);
//            }
            String tradeNo = timestamp + idStr;
            return tradeNo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void updateAccountDetail(Transaction parse) {
        //更新订单状态
        Map<String, Object> map = new HashMap<>();
        map.put("tradeNo", parse.getOutTradeNo().toString());
        map.put("transactionId", parse.getTransactionId().toString());
        orderMapper.updateOrderStatus(map);
        //保存充值流水账单
        String outTradeNo = parse.getOutTradeNo();
        Map<String, Object> accountMap = accountUserMapper.getAccountUser(outTradeNo);
        Map<String, Object> billMap = new HashMap<>();
        billMap.put("id", IdTool.getIdStr());
        billMap.put("amount", parse.getAmount().getTotal());
        billMap.put("accountUserId", accountMap.get("accountUserId"));
        billMap.put("payOrderId", accountMap.get("payOrderId"));
        billMap.put("agoBalance", accountMap.get("balance"));
        billMap.put("createDate", DateUtil.getTime());
        billMap.put("laterBalance", BigDecimal.valueOf(parse.getAmount().getTotal()).add(BigDecimal.valueOf(Integer.valueOf(accountMap.get("balance").toString()))));
        billMap.put("billType", "pay");
        billMap.put("tradeType", "wechat-applet");
        log.info("-----------------------本次支付流水账单信息：" + billMap);
        orderMapper.insertBillLog(billMap);

        //更新户号的余额
        Map<String, Object> accountUserMap = new HashMap<>();
        accountUserMap.put("accountUserId", accountMap.get("accountUserId"));
        accountUserMap.put("balance", Long.valueOf(parse.getAmount().getTotal()) + Long.valueOf(accountMap.get("balance").toString()));
        accountUserMapper.updateBalance(accountUserMap);
    }*/
}